import uniRequest from "./uni-request/index.js";
import ProjectConfig from "@/static/config.base.js";
import {
	getToken
} from "../storage/index.js";

// 全局配置
uniRequest.defaults.baseURL = ProjectConfig.baseUrl;
uniRequest.timeout = 1000 * 60; // 请求超时时间
uniRequest.interceptors.request.use(
	(config) => {
		const isToken = (config.headers || {}).isToken === false;
		const token = getToken();
		config.params = config.params || {};
		config.headers["Authorization"] = "Bearer " + token
		if (config.method == "get") {
			config.headers["Content-Type"] = "application/x-www-form-urlencoded; text/plain; charset=UTF-8";

		}
		if (config.method == "post" || config.method == "put") {
			config.headers["Content-Type"] = config.headers["Content-Type"] || "application/json; charset=UTF-8";
		}
		return config;
	},
	(error) => {
		// console.log('请求拦截报错', error)
		return error;
	}
);
uniRequest.interceptors.response.use(
	(request) => {
		// console.log('响应拦截', request)
		return request;
	},
	(error) => {
		// console.log('响应拦截报错', error)
		return error;
	}
);

const request = (config) => {
	return new Promise((resolve, reject) => {
		uniRequest
			.request(config)
			.then((res) => {
				if (res.data.code == "401") {
					uni.reLaunch({
						url: "/pages/Login/Login",
					});
				}
				resolve(res.data);
			})
			.catch((err) => {
				reject(err);
			});
	});
};
export default request;